package com.opages.mvc.adapter.openfeign.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
/**
 * 将请求头中带有opages-前缀的信息转发到后方,用于cloud调用mvc,mvc再调用其它mvc时可以附带信息过去
 * @Author daizhong.liu
 * @Date 2020/7/15 17:42
 **/
public class FeignRequestInterceptor implements RequestInterceptor {
    public static final String HEADER_PREFIX = "opages-";

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 将当前请求的头信息传递下去
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        if (requestAttributes == null) {
            return;
        }
        HttpServletRequest request = requestAttributes.getRequest();
        if (request == null) {
            return;
        }
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames == null) {
            return;
        }
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            if (!name.toLowerCase().startsWith(HEADER_PREFIX.toLowerCase())) {
                continue;
            }
            requestTemplate.header(name, request.getHeader(name));
        }
    }
}
